import React from 'react';
import { NavLink, Route } from 'react-router-dom';
import BackNav from 'shared/components/BackNav';
import localStorage from 'shared/utils/localStorage';
import { fetchInvoiceList } from '../api';
import NormalInvoiceForm from './NormalInvoiceForm';
import SpecialInvoiceForm from './SpecialInvoiceForm';
import './index.less';

const tabselected = require('src/static/tabselected.png');

export default class InvoiceForm extends React.PureComponent {
  state = {
    formData: {},
    formData2: {},
  }

  componentDidMount() {
    fetchInvoiceList().then((res) => {
      if (res.code === 1000 && res.data.length > 0) {
        const dataLength = res.data.length - 1;
        if (res.data[dataLength].invoice_type === '2') {
          __self.history.push('/InvoiceForm/special-invoice')
          this.setState({ formData2: res.data[dataLength] })
        } else {
          this.setState({ formData: res.data[dataLength] })
        }
      }
    })
  }

  renderInvoiceFormTabs() {
    const { url } = this.props.match;
    const tabsData = [
      { path: `${url}/electronic-normal-invoice`, title: '电子普通发票' },
      {path: `${url}/special-invoice`, title: '增值税专用发票'},
    ]
    return tabsData.map((value, index) => (
      <NavLink key={index} to={`${value.path}`} activeClassName="active">
        {value.title}
        <img src={tabselected} alt='' />
      </NavLink>
    ))
  }

  render() {
    const { url } = this.props.match;
    const { formData, formData2 } = this.state;
    const backToLink = localStorage.get('nowPaymentPath');
    return ([
      <BackNav key="back-nav" title="发票" to={backToLink} />,
      <div className="invoice-form" key="invoice-form">
        <div className="invoice-form-title">
          <span>发票信息</span>
        </div>
        <div className="invoice-form-tabs">
          {this.renderInvoiceFormTabs()}
        </div>
        <div className="invoice-form-content">
          <Route
            path={`${url}/electronic-normal-invoice`}
            component={() => <NormalInvoiceForm formData={formData} backToLink={backToLink} />}
          />
          <Route
            path={`${url}/special-invoice`}
            component={() => <SpecialInvoiceForm formData={formData2} backToLink={backToLink} />}
          />
        </div>
      </div>
    ])
  }
}